import React, {Component} from 'react';
import {message, Modal, Tree} from 'antd';
import {RoleApi} from '@/api/index'

export default class Authz extends Component {

    constructor(props) {
        super(props);
        this.state = {
            modalVisible: false,
            list: [],
            code: null,
            checkedKeys: [],
            expandedKeys: [1],

        };
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.modalVisible !== this.state.modalVisible) {
            this.setState({
                modalVisible: nextProps.modalVisible,
                code: nextProps.code
            }, () => {
                this.getPermiss()
            });
        }
    }

    handleOk = async () => {
        let params = {}
        params.roleCode = this.state.code
        params.permissIds = this.state.checkedKeys
        let ret = await RoleApi.authz(params);
        if (ret && ret.code === 200) {
            message.success('角色授权成功');
            this.handleCancel()
        }
    };

    handleCancel = async () => {
        this.props.onClose && this.props.onClose()
        this.setState({
            modalVisible: false,
        });
    };

    getPermiss = async () => {
        let ret = await RoleApi.rolePermiss({code: this.state.code});
        if (ret && ret.code === 200) {
            this.setState({
                list: ret.data.permissList,
                checkedKeys:ret.data.keys
            });
        }
    }

    onCheck = (checkedKeys, info) => {
        this.setState({checkedKeys: checkedKeys.checked})
    };

    render() {

        const {modalVisible} = this.state

        return (
            <Modal
                title="角色授权"
                open={modalVisible}
                onOk={this.handleOk}
                onCancel={this.handleCancel}
                destroyOnClose="true"
                bodyStyle={{height:500,overflowY:'scroll'}}
            >
                <Tree
                    checkable
                    checkStrictly
                    onCheck={this.onCheck}
                    checkedKeys={this.state.checkedKeys}
                    treeData={this.state.list}
                />
            </Modal>
        );
    }
}